<template>
    <div class="managemusic">
        <!-- 音乐播放器 -->
        <audio :src="listenMusicSrc" autoplay ref="musicPlayer"></audio>

        <!-- 头部 -->
        <Row style="padding:20px 60px 20px 0px;">
            <!-- 搜索框 -->
            <Col span="5">
            <Input v-model="searchName" prefix="ios-musical-notes" clearable style="width:auto;"
                placeholder="请输入歌手或歌曲进行搜索" @keypress.enter.native="searchSong" />
            </Col>
            <!-- 试听歌曲按钮，点击这个显示所有歌曲的模态框 -->
            <Col span="7">
            <Button type="primary" style="margin-left:0px;" @click="toListen = true">试听歌曲</Button>
        </Col>
        <!-- 试听歌曲按钮，点击这个按钮，显示所有歌曲的模态框 -->
            <!-- <Col span="4">
                    <Button type="success" style="margin-left:0px;">所有歌曲</Button>
                    </Col> -->
            <!-- 歌曲控制是否播放以及添加按钮 -->
            <Col span="12" style="text-align:right;">
            <!-- 控制歌曲的播放以及歌曲播放时候的动画 -->
            <Avatar v-if="listenMusicPoster" class="listen-poster" size="large" style="margin-right:40px;"
                :src="listenMusicPoster" @click.native="operateMusic"
                :style="{ 'animation-play-state': animationPlayState }" />
            </Col>
        </Row>

        <!-- 歌曲数据表-->
        <div style="width: 100%;background-color: #f40;">
            <el-table :data="allSongs" border style="width: 100%">
                <el-table-column type="index" label="序号" align="center" width="60">
                </el-table-column>
                <el-table-column prop="_id" label="歌曲ID" align="center" width="240">
                </el-table-column>
                <el-table-column prop="songName" label="歌曲名称" align="center" width="200">
                </el-table-column>
                <el-table-column prop="artist" label="歌手名称" align="center" width="170">
                </el-table-column>
                <el-table-column prop="src" label="歌曲地址" align="center" width="230">
                </el-table-column>
                <el-table-column label="歌曲封面" align="center" width="200">
                    <template slot-scope="scope">
                        <Avatar :src="'http://localhost:3000/api/admin/poster?img=' + scope.row.poster" size="large" />
                    </template>
                </el-table-column>
                <el-table-column prop="language" label="语种" align="center" width="120">
                </el-table-column>
                <el-table-column prop="style" label="歌曲风格" align="center" width="120">
                </el-table-column>
                <el-table-column prop="playCount" label="点播次数" align="center" width="80">
                </el-table-column>
                <el-table-column prop="date" label="更新时间" align="center" width="200">
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right" align="center">
                    <template slot-scope="scope">
                        <!-- 删除 -->
                        <el-tooltip class="item" effect="dark" content="取消收藏" placement="top">
                        <el-button type="danger"
                            size="samll"
                            circle
                            icon="el-icon-delete"
                            @click="onDeleteSong(scope.row)">
                        </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <Row>
            <Col span="24" style="text-align: right;padding:0 10px;">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page.sync="paginations.pageIndex" :page-sizes="paginations.pageSizes"
                :page-size="paginations.pageSize" :layout="paginations.layout" :total="paginations.total">
            </el-pagination>
            </Col>
        </Row>

        <!-- 密码验证对话框 -->
        <Modal width="360" draggable v-model="isCheckPassword" :mask-closable="false">
            <p slot="header" style="color:#f60;">
                <Icon type="ios-information-circle"></Icon>
                <span>验证密码</span>
            </p>
            <div style="text-align:left;font-size: 14px;">
                <Row>
                    <Col span="18">
                    <!--不加enter的话，输入密码时会一直响应，在组件使用要加native-->
                    <!-- 组件响应原生事件，要加native。Input是组件 -->
                    <Input type="password" icon="ios-key" placeholder="请输入管理员密码..." v-model="inputPassword"
                        @keyup.enter.native="checkPwd()" />
                    </Col>
                    <Col span="6">
                    <el-button type="primary" size="small" @click="checkPwd()">验证</el-button>
                    </Col>
                </Row>
            </div>
            <div slot="footer"></div>
        </Modal>

        <!-- 音乐试听对话框 -->
        <Modal width="700" v-model="toListen">
            <p slot="header" style="color:#f60;text-align: center;">
                <Icon type="ios-musical-notes" />
                <span>点击试听</span>
            </p>
            <div style="100%">
                <el-table :data="allSongs" height="300" style="width: 100%;">
                    <el-table-column prop="songName" align="center" width="200" label="歌名"></el-table-column>
                    <el-table-column prop="artist" align="center" width="200" label="歌手"></el-table-column>
                    <el-table-column align="center" width="200" label="试听">
                        <template slot-scope="scope">
                            <span class="toListen-link" @click="listenMusic(scope.row)">播放</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div slot="footer" style="height:30px">
                <Col span="24" style="text-align: right;padding:0px 0px">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page.sync="paginations.pageIndex" :page-sizes="paginations.pageSizes"
                    :page-size="paginations.pageSize" :layout="paginations.layout" :total="paginations.total">
                </el-pagination>
                </Col>
            </div>
        </Modal>
    </div>
</template>

<script>
export default {
    name: 'managemusic',
    data() {
        return {
            // 试听歌曲
            toListen: false,
            listenMusicSrc: '',
            listenMusicPoster: '',
            animationPlayState: 'running', //动画运行状态 running 播放 paused 暂停

            // 验证密码
            isCheckPassword: false,
            inputPassword: '',
            // 展示在页面上的每一页的所有歌曲
            allSongs: [],
            // 是所有的歌曲，和数据库中的歌曲保持一致
            allTableSongs: [],

            // 搜索关键字
            searchName: '',

            // 分页
            paginations: {
                pageIndex: 1,// 当前位于哪一个页面
                total: 0,//总个数
                pageSize: 5,// 每一页显示多少条
                pageSizes: [5, 10, 15, 20, 25],
                layout: "sizes, prev, pager, next, jumper, total" // 翻页的属性
            },
        }
    },
    created() {
        this.getAllSong()
    },
    watch: {
        searchName: function () {
            // 如果searchName为"",那么获取全部的歌曲列表
            if (this.searchName === '') {
                this.getAllSong()
            }
        }
    },
    methods: {
        // 验证管理员密码
        checkPwd() {
            console.log('checkPwd')
            // 获取输入的密码
            const inputPassword = this.inputPassword.trim()
            if (inputPassword.length > 0) {
                // 把密码验证框给关闭
                this.isCheckPassword = false

                // 把这个密码发到服务端去校验
                this.$axios.post('http://localhost:3000/api/admin/islegal', {
                    password: inputPassword,
                    email: this.$store.getters.adminInfo.email
                }).then(res => {
                    // 把表单中的数据给发送到服务端
                    // 提交添加音乐对话框表单中的数据
                    console.log('islegal res=>', res)
                    if (res.data.result == "true") {
                        if (this.flag == 3) { // 删除
                            this.$axios.post('http://localhost:3000/api/admin/music/deleteLikeSong', { _id: this.delRow._id })
                                .then(res => {
                                    console.log('删除歌曲返回res=>', res.data)
                                    // 刷新列表
                                    this.getAllSong()

                                    // 清空数据
                                    this.inputPassword = ""
                                    this.$Message.success('删除成功')
                                })
                        }
                    }
                }).catch(err => {
                    alert('密码错误')
                    this.inputPassword = ""
                })
            } else {
                this.isCheckPassword = false
                this.$Modal.warning({
                    title: '提示',
                    content: '密码不能为空，请输入管理员口令',
                    onOk: () => {
                        this.isCheckPassword = true
                    }
                })
            }
        },
        // 根据歌曲或者歌手名称搜索
        searchSong() {
            this.$axios.post('http://localhost:3000/api/admin/searchByName', {
                searchName: this.searchName
            }).then(res => {
                this.allTableSongs = res.data.result // 所有的歌曲 12条数

                // 分页
                this.paginations.total = this.allTableSongs.length
                this.paginations.pageIndex = 1
                this.paginations.pageSize = 5

                this.allSongs = this.allTableSongs.filter((item, index) => { // 过滤之后，只剩下5条数据了。
                    return index < this.paginations.pageSize
                })
            })
        },

        // 获取所有的歌曲
        getAllSong() {
            this.$axios.get('http://localhost:3000/api/admin/alllikes')
                .then(res => {
                    console.log('getAllSong res=>', res)
                        this.allTableSongs = res.data.result // 所有的歌曲 12条数

                        // 分页
                        this.paginations.total = this.allTableSongs.length
                        this.paginations.pageIndex = 1
                        this.paginations.pageSize = 5

                        this.allSongs = this.allTableSongs.filter((item, index) => { // 过滤之后，只剩下5条数据了。
                            return index < this.paginations.pageSize
                        })                   
                }).catch(err => {
                    this.$Message.error(err)
                })
        },
        // 当前页，页码改变
        handleCurrentChange(page) {
            console.log('当前页=>', page)
            // 在前端分页
            // 获取当前页的数量
            // 0~4 5~9 10~11
            let sortNum = this.paginations.pageSize * (page - 1) // 5
            const tableData = this.allTableSongs.filter((item, index) => {
                return index >= sortNum
            })
            console.log('tableData=>', tableData)
            // this.allSongs = tableData.filter((item,index)=>{
            //     return index < this.paginations.pageSize
            // })
            this.allSongs = tableData.slice(0, 5)
        },
        // 改变每页条数
        handleSizeChange(pageSize) {
            console.log('每一页个数=>', pageSize)
            this.paginations.pageIndex = 1
            this.paginations.pageSize = pageSize

            this.allSongs = this.allTableSongs.slice(0, pageSize)
        },
        // 试听歌曲
        listenMusic(song) {
            console.log('试听歌曲song=>', song)
            this.listenMusicSrc = `http://localhost:3000/api/admin/musicByLikeSongId?id=${song._id}`
            this.listenMusicPoster = 'http://localhost:3000/api/admin/poster?img=' + song.poster
        },
        // 控制音乐的播放和暂停
        operateMusic() {
            //控制音乐播放和暂停 audio有个状态paused，为true表示停止，否则播放
            //控制动画的开启和关闭
            // console.log("musicPlayer",this.$refs.musicPlayer);
            // console.dir(this.$refs.musicPlayer)  //查看详细信息
            if (this.$refs.musicPlayer.paused) {// 暂停的状态
                // 开启播放
                this.$refs.musicPlayer.play()
                // 开启动画
                this.animationPlayState = 'running'
            } else {// 播放的状态
                // 暂停播放
                this.$refs.musicPlayer.pause()
                // 停止动画
                this.animationPlayState = 'paused'
            }
        },
        // 取消收藏
        onDeleteSong(song) {
            console.log('删除歌曲song=>', song)
            // 弹框提示是否删除
            this.$confirm(`确定删除${song.songName}(${song.artist})歌曲吗？不可撤销，是否继续?`,
                "风险提示",
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).then(() => {
                this.isCheckPassword = true
                this.flag = 3
                this.delRow = song
                console.log('删除的歌曲=>', this.delRow)
            }).catch(err => {
                // 点击取消后进入这里执行
                console.log('取消：', err)
            })
            // 验证密码
        }
    }
}
</script>

<style lang="less" scoped>
.managemusic {
    height: 100vh;
    overflow-y: scroll;
    padding-bottom: 100px;
    padding-left: 10px;
    .listen-poster {
        cursor: pointer;
        animation: poster 15s linear infinite;
    }
    @keyframes poster {
        from {
            transform: rotate(0deg);
        }
        to {
            transform: rotate(360deg);
        }
    }
}
.toListen-link {
    cursor: pointer;

    &:hover {
        color: rgb(223, 107, 72)
    }
}
</style>